<template>
	<lay-form-item :label="label" :prop="propName" v-bind:required="isRequired ? true : null" :rules="codeRule" style="margin-bottom: 0px !important">
		<lay-input :placeholder="placeholderCode" v-model="inputValue" allow-clear :disabled="isDisabled" @input="handleInput" @blur="handleBlur"></lay-input>
	</lay-form-item>
</template>

<script setup>
	import { ref, reactive, watch } from 'vue';

	import common from '@/utils/common';
	const props = defineProps({
		label: {
			type: String,
			default: '编号',
		},
		propName: {
			type: String,
			default: 'Code',
		},
		opType: {
			type: String,
			default: '',
		},
		value: {
			type: String,
			default: '',
		},
		rule: {
			type: Object,
			default: () => {},
		},
		allowEdit: {
			type: Boolean,
			default: false,
		},
	});

	const inputValue = ref(props.value);
	// 监听props.value的变化
	watch(
		() => props.value,
		(newValue, oldValue) => {
			inputValue.value = newValue;
		}
	);

	//判断表单是否是自动生成
	const isRequired = ref(true);
	const placeholderCode = ref('请输入' + props.label);
	const isAutoCode = common.isAutoGenCode();
	if (isAutoCode == true || isAutoCode == 'true') {
		placeholderCode.value = '自动生成，可不填';
		isRequired.value = false;
	}

	const isDisabled = ref(false);
	if (props.opType == 'add') {
		//新增时，允许操作
		isDisabled.value = false;
	} else {
		//修改时，要结合判断allowEdit
		isDisabled.value = !props.allowEdit;
	}

	//事件
	const emit = defineEmits(['input', 'blur']);

	//获取输入的值
	function handleInput(value) {
		// 当需要更新数据时，发出事件给父组件
		emit('input', value);
	}
	//鼠标离开表单时
	function handleBlur(e) {
		// 当需要更新数据时，发出事件给父组件
		emit('blur', inputValue.value);
	}

	//验证编号的输入是否合法
	let codeRule = ref({});
	if (props.rule) {
		codeRule.value = props.rule;
	} else {
		codeRule.value = {
			//   pattern: /^[0-9a-zA-Z_]{1,}$/,
			validator: (rule, value, callback) => {
				const regex = /^[0-9a-zA-Z_]{1,}$/;
				if (value != '') {
					if (!regex.test(value)) {
						callback(new Error('只允许输入数字、26个英文字母或者下划线'));
					} else {
						return true;
					}
				}
				return true;
			},
		};
	}
</script>

<style></style>